#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
typedef pair<int,int> pii;
vector<int> dx={0,0,1,-1},dy={1,-1,0,0};
const int INF=0x3f3f3f3f;
    int minTimeToReach(vector<vector<int>>& moveTime) {
        priority_queue<tuple<int,int,int>,vector<tuple<int,int,int>>,greater<>> q;
        q.emplace(0,0,0);
        int n=moveTime.size();
        int m=moveTime[0].size();
        vector<vector<int>> d(n,vector<int>(m,INF));
        d[0][0]=0;
        while(!q.empty())
        {
            auto [d_x,x,y]=q.top();
            q.pop();
            if(x==n-1&&y==m-1) return d_x;
            if(d_x>d[x][y]) continue;
            int count=(x+y)%2+1;
            for(int i=0;i<4;++i)
            {
                int cx=x+dx[i];
                int cy=y+dy[i];
                if(cx>=0&&cx<n&&cy>=0&&cy<m&&max(d_x,moveTime[cx][cy])+count<d[cx][cy])
                {
                    d[cx][cy]=max(d_x,moveTime[cx][cy])+count;
                    q.emplace(d[cx][cy],cx,cy);
                }
            }
           
        }
         return d[n-1][m-1];
    }
};